package club.caihappy.store.controller;

import club.caihappy.store.controller.ex.*;
import club.caihappy.store.entity.User;
import club.caihappy.store.service.IUserService;
import club.caihappy.store.service.ex.InsertException;
import club.caihappy.store.service.ex.UsernameDuplicatedException;
import club.caihappy.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by DELL on 2022/2/27
 **/
@RestController // @Controller+@ResponseBody
@RequestMapping("users")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    //@ResponseBody//表示此方法的响应结果以json格式进行数据的响应给到前端
    @RequestMapping("reg")
    public JsonResult<Void> reg(User user) {
        userService.reg(user);
        return new JsonResult<>(OK, "用户注册成功");
    }

    @RequestMapping("login")
    public JsonResult<User> login(String username, String password, HttpSession session) {
        User data = userService.login(username, password);
        //向session对象中完成数据的绑定(全局的session)
        session.setAttribute("uid", data.getUid());
        session.setAttribute("username", data.getUsername());

        return new JsonResult<User>(OK, "用户登陆成功", data);
    }

    @RequestMapping("change_password")
    public JsonResult<Void> changePassword(HttpSession session, String oldPassword, String newPassword) {
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changePassword(uid, username, oldPassword, newPassword);
        return new JsonResult<Void>(OK, "修改成功");
    }


    @RequestMapping("get_by_uid")
    public JsonResult<User> getByUid(HttpSession session) {
        User user = userService.getByUid(getUidFromSession(session));
        return new JsonResult<>(OK, user);
    }


    //修改用户数据
    @RequestMapping("change_info")
    public JsonResult<Void> changeInfo(HttpSession session, User user) {
        userService.changeInfo(getUidFromSession(session), getUsernameFromSession(session), user);
        return new JsonResult<>(OK, "用户数据修改成功");
    }


    //设置上传文件的最大值
    public static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;

    //设置上传文件的类型
    public static final List<String> AVATAR_TYPE = new ArrayList<>();

    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");
    }

    //修改用户头像
    @RequestMapping("change_avatar")
    public JsonResult<String> changeAvatar(HttpSession session, MultipartFile file) {

        if (file.isEmpty()) {
            throw new FileEmptyException("文件为空");
        }
        if (file.getSize() > AVATAR_MAX_SIZE) {
            throw new FileSizeException("文件超出限制");
        }
        if (!AVATAR_TYPE.contains(file.getContentType())) {
            throw new FileTypeException("文件类型不支持");
        }
        //上传的文件的根路径E:/upload/文件.png
        String parent = "E:/upload/";
        //File对象指向这个路径，File路径是否存在，不存在就创建路径
        File dir = new File(parent);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        //获取到这个文件的名称，通过UUID获取随机字符串作为文件名

        int index = file.getOriginalFilename().lastIndexOf(".");
        //获取后缀名
        String suffix = file.getOriginalFilename().substring(index);
        String filename = UUID.randomUUID().toString().toUpperCase() + suffix;
        File dest = new File(dir, filename);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new FileUploadIOException("文件读写异常");
        }
        System.out.println(dest.getAbsolutePath());
        String avatar = "/upload/" + filename;
        userService.changeAvatar(getUidFromSession(session), avatar, getUsernameFromSession(session));
        return new JsonResult<>(200, "头像修改成功", avatar);
    }


/*
    //@ResponseBody//表示此方法的响应结果以json格式进行数据的响应给到前端
    @RequestMapping("reg")
    public JsonResult<Void> reg(User user) {
        //创建响应结果对象
        JsonResult<Void> jsonResult = new JsonResult<>();

        try {
            userService.reg(user);
            jsonResult.setState(200);
            jsonResult.setMessage("用户注册成功");
        } catch (UsernameDuplicatedException e) {
            jsonResult.setState(4000);
            jsonResult.setMessage(e.getMessage());
        } catch (InsertException e) {
            jsonResult.setState(5000);
            jsonResult.setMessage(e.getMessage());
        }
        return jsonResult;
    }
*/
}
